import React, {PureComponent} from 'react';
import SubTable from './subTable';
import ModalStep2 from './modal';
import './index.less'

import {
    Row,
    Col,
    Table,
    Form,
    Cascader,
    Icon,
    Button,
    Input,
    Select,
    DatePicker,
    Radio,
    TreeSelect,
    message,
    Upload,
    Spin,
    Alert,
    Modal,
    Checkbox
} from 'antd'
import Fetch from "../../../../../fetchAPI";
import tools from "../../../../../utils/tools";

const {TextArea} = Input;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const {RangePicker} = DatePicker;
const Option = Select.Option;
const headLayout = {
    span: 8
}


class Step3 extends PureComponent {
    constructor(props) {
        super(props)
    }

    data = {
        pageIndex: 1,
        pageSize:20
    }
    state = {
        brandList: [],
        commoditytreeData: [],
        commodityList: [],
        expandedRowKeys: [],
        selectedRows: [],
        total: 0,
        ERPlist: [],
        productNo: [],
        showModal: false,
        presellTableLoading: false,
        inventoryModal:false,
        inventoryFileList: [],
    }

    componentDidMount() {
        this.getAllBrand();

        this.getAllType();
        this.getPresaleList();
        this.getAllERPType();
    }

    expandedRowRender = (res) => {

        return (<SubTable {...this.props} onDataReset={this.getPresaleList} data={res}></SubTable>);
    };
    onExpandedRowsChange = (indexArr) => {

        const item = this.state.commodityList[indexArr[indexArr.length - 1]] || {};
        const {productNo} = item;
        if (productNo) {
            this.setState({
                expandedRowKeys: [indexArr[indexArr.length - 1]]
            })
            Fetch.getSku({id: productNo}).then(res => {

                if (res && res.code === '200') {
                    item.subTableData = res.result;
                    setTimeout(() => {
                        this.setState({
                            expandedRowKeys: [indexArr[indexArr.length - 1]]
                        })
                    })

                }

            });
        } else {
            this.setState({
                expandedRowKeys: []
            })
        }


    }
    getAllType = () => {
        return Fetch.getAllType().then((res) => {
            this.setState({
                commoditytreeData: tools.deepCopy((tools.listToTree('key', 'text', res.result)), 'label')

            })
        })
    }
    getAllERPType = () => {
        return Fetch.getAllERPType().then((res) => {
            this.setState({
                ERPlist: tools.deepCopy((tools.listToTree('key', 'text', res.result)), 'label')

            })
        })
    }
    getAllBrand = () => {
        return Fetch.getAllBrand().then((res) => {
            this.brandList = res.result;
        })
    }
    brandSearch = (value) => {
        value = value.replace(/^\s*|^\s$/, '');
        console.log(value.length);
        if (value[0] === ">" && value.length > 1) {
            console.log(value[0])
            this.setState({
                brandList: this.brandList.map((item) => {
                    return {
                        value: item.key,
                        name: item.vaule,

                    }
                }).filter((item) => {
                    return (item.name && item.name[0].toUpperCase() === value[1].toUpperCase());
                })
            })
        } else if (value !== '' && (value.length > 2)) {
            let reg=new RegExp(value,'i');
            this.setState({
                brandList: this.brandList.map((item) => {
                    return {
                        value: item.key,
                        name: item.vaule
                    }
                }).filter((item) => {
                    return (item.name && item.name.search(reg) !== -1);
                })
            })
        }

    }
    searchEnter = () => {
        this.data.pageIndex = 1;
        this.getPresaleList();
    }
    getPresaleList = () => {
        this.setState({
            presellTableLoading: true
        })
        const {pid, id} = this.props.location.query;
        const value = this.props.form.getFieldsValue();

        const {shopType, ERPtype, select_brand, SPUcode} = value;
        let listString = SPUcode.replace(/^([\s↵]+)|([\s↵]+)$/g, '');
        const SPUcodeList = listString.split(/[\s↵]+/);
        Fetch.getPresaleList({
            id: pid,
            presaleId: id,
            categoryNo: shopType && shopType.join(','),
            erpCategoryNo: ERPtype && ERPtype.join(','),
            brandNo: select_brand && select_brand.join(','),
            productNo: SPUcodeList&&SPUcodeList[0]?SPUcodeList:[],
            pageIndex: this.data.pageIndex,
            pageSize:this.data.pageSize
        }).then(res => {
            this.setState({
                commodityList: res.result ? res.result.map((item, index) => {
                    return {...item, key: index}
                }) : [],
                total: res.rowCount,
                presellTableLoading: false,
                expandedRowKeys: []
            })
        })

    }
    removeItem = (item) => {
        const {pid, id} = this.props.location.query;
        return () => {

            Modal.confirm({
                title: (<div>您确定要停止预售并删除编号为 <span style={{color: 'red'}}>{item.productNo}</span> 的<span
                    style={{color: 'red'}}>{item.productName}</span>吗？</div>),
                onOk:()=> {
                    Fetch.presaleProductDel({
                        "presaleId": id,
                        "rangeConditionId": pid,
                        "productNos": [item.productNo]
                    }).then((res) => {
                        if (res.code === '200') {
                            message.success('操作成功了！');
                            this.getPresaleList();
                        }
                    })
                },
            })
        }
    }
    removeSelectd = () => {
        const {pid, id} = this.props.location.query;
        const {selectedRows} = this.state;
        if (selectedRows.length > 0) {
            Modal.confirm({
                title: (<div>您确定要停止预售并删除选中的商品吗？</div>),
                onOk:()=> {
                    Fetch.presaleProductDel({
                        "presaleId": id,
                        "rangeConditionId": pid,
                        "productNos": selectedRows
                    }).then((res) => {
                        if (res.code === '200') {
                            message.success('操作成功了！');
                            this.getPresaleList();
                        }
                    })
                },
            })
        }

    }
    reset = () => {
        this.setState({
            promotionIcon: [],
            presellBackground: [],
        });
        this.props.form.resetFields();
    }
    addShop = () => {
        this.setState({
            showModal: true
        })
    }
    HideModal = (obj) => {
        return () => {
            if (obj && obj.cancle) {
                this.setState({
                    showModal: false,
                    inventoryModal:false,
                    inventoryFileList:[]

                })
                return;
            } else {
                this.setState({
                    showModal: false,
                    inventoryModal:false,
                    inventoryFileList:[]
                })
                this.getPresaleList()
            }


        }

    }
    importInventory=()=>{
      this.setState({
          inventoryModal:true
      })
    }
    importInventoryEnter=()=>{
      const {validateFields} = this.props.form;
      validateFields(['inventoryExcelFile'],(err,value)=>{
          console.log(value)
          if(!err){
              let formData = new FormData();
              formData.append("file",value['inventoryExcelFile'].file);
              Fetch.importInventory(formData).then((res)=>{
                  console.log(res)
                  if(res){
                      if(res.code==="200"){
                          message.success('上传成功');
                          setTimeout(()=>{
                              this.HideModal({cancle: true})();
                          },100)

                      }else{
                          message.error(res.message);
                      }
                  }else{
                      message.error('服务器错误');
                  }
              })
          }

      });

    }
    downLoad = () => {
        window.location.href = require('../../../../../localData/ImportQuantity.xls');
    }
    render() {
        const {getFieldDecorator,validateFields, setFieldsValue,getFieldsError, getFieldError, isFieldTouched, isFieldsTouched} = this.props.form;
        const {brandList, commoditytreeData, showModal,inventoryModal,inventoryFileList, presellTableLoading, commodityList, expandedRowKeys, total, ERPlist} = this.state;
        const itemLayout = {
            labelCol: {
                span: 6
            },
            wrapperCol: {
                span: 17
            }
        }
        const excelLayout = {
            colon: false,
            labelCol: {
                span: 6
            },
            wrapperCol: {
                span: 18
            }
        }

        const imports1={
            onRemove: (file) => {
                console.log(file)
                this.setState((state) => {
                    return {
                        inventoryFileList: [],
                    };
                });
                setFieldsValue({inventoryExcelFile:''});
                validateFields(['inventoryExcelFile'],(err,value)=>{});
            },
            beforeUpload: (file) => {
                this.setState(state => ({
                    inventoryFileList: [file],
                }));
                return false;
            },
            fileList:inventoryFileList,
        };
        const columns1 = [
            {
                title: '商品信息', key: 'name', render: (item) => {
                    const {
                        productNo,
                        productPicFile,
                        productName,
                        brandEnName,
                        userGroupName,
                        userName,
                        virtualAreaName,
                        shopFirstCategoryName,
                        shopFourCategoryName
                    } = item;
                    return (
                        <div className={'item1_wrap'}>
                            <div className={'item_info_img'}>
                                <p>SPU:{productNo}</p>
                                <img src={productPicFile} alt=""/>
                            </div>
                            <div className={'item_info_text'}>
                                <p><span>品类：</span><b>{`${shopFirstCategoryName} / ${shopFourCategoryName}`}</b></p>
                                <p><span>品牌：</span><b>{brandEnName}</b></p>
                                <p><span>名称：</span><b>{productName}</b></p>
                                <p><span>负责组：</span><b>{userGroupName}</b></p>
                                <p><span>负责人：</span><b>{userName}</b></p>
                                <p><span>虚拟区域：</span><b>{virtualAreaName}</b></p>
                            </div>
                        </div>

                    )
                }
            },
            {
                width: 350, title: '库存信息', key: 'platform', render: (item) => {
                    const {
                        presaleQuantity,
                        availableStock
                    } = item;
                    return (
                        <div className={'item2_wrap'}>
                            <div className={'item_info_text'}>
                                <p><span>商品总库存：</span><b>{availableStock}</b></p>
                            </div>
                        </div>

                    )
                }
            },
            {
                width: 300, title: '操作信息', key: 'version', render: (item) => {
                    const {
                        createUserName,
                        createDate,
                        updateUserName,
                        updateDate
                    } = item;
                    return (
                        <div className={'item3_wrap'}>
                            <div className={'item_info_text'}>
                                <p><span>创建人：</span><b>{createUserName}</b></p>
                                <p><span>时间：</span><b>{createDate}</b></p>
                                <p><span>修改人：</span><b>{updateUserName}</b></p>
                                <p><span>时间：</span><b>{updateDate}</b></p>
                            </div>
                        </div>

                    )
                }
            },
            {
                width: 200, title: '操作', key: 'upgradeNum', render: (item) => {
                    return (
                        <div className={'item4_wrap'}>
                            <div className={'item_info_text'}>
                                <Button onClick={this.removeItem(item)} type={'primary'}>停止预售并移除商品</Button>
                            </div>
                        </div>

                    )
                }
            },
        ];
        const rowSelection = {
            // selectedRowKeys:this.state.selectedRows,
            // fixed: false,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRowKeys);
            },
            onSelect: (record, selected, selectedRows) => {
                console.log(selectedRows);
                this.setState({
                    selectedRows: selectedRows.map((item) => {
                        return item.productNo
                    })
                })
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                this.setState({
                    selectedRows: selectedRows.map((item) => {
                        return item.productNo
                    })
                })
            },
        };
        return (<div className={'step3'}>
            <Form>
                <div className="step3Head">
                    <Row>
                        <Col {...headLayout}>
                            <Form.Item
                                label={'SPU编号：'}
                                {...itemLayout}
                            >
                                {getFieldDecorator('SPUcode', {
                                    initialValue: '',
                                    rules: [{
                                        transform: function (value) {
                                            return value && value.replace(/^([\s↵]+)|([\s↵]+)$/g, '')
                                        }
                                    }]
                                })(
                                    <TextArea autosize={{minRows: 1 , maxRows:20}} placeholder={'可输入多个编号 使用空格或换行隔开'}
                                              rows={1}></TextArea>
                                )}
                            </Form.Item>
                        </Col>
                        <Col {...headLayout}>
                            <Form.Item
                                label={'商城分类：'}
                                {...itemLayout}
                            >
                                {getFieldDecorator('shopType', {
                                    rules: [],
                                })(
                                    <Cascader
                                        placeholder={'请选择商城分类'}
                                        changeOnSelect={true}
                                        options={commoditytreeData}/>
                                )}
                            </Form.Item>
                        </Col>
                        <Col {...headLayout}>
                            <Form.Item
                                label={'ERP分类：'}
                                {...itemLayout}
                            >
                                {getFieldDecorator('ERPtype', {
                                    rules: [],
                                    initialValue: []
                                })(
                                    <Cascader
                                        placeholder={'请选择ERP分类'}
                                        changeOnSelect={true}
                                        options={ERPlist}
                                    />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>

                        <Col span={12}>
                            <Form.Item
                                label={'品牌：'}
                                labelCol={{
                                    span: 4
                                }}
                                wrapperCol={{
                                    span: 18
                                }}
                            >
                                {getFieldDecorator('select_brand', {
                                    // rules: [{required: true, message: '请选择预售发货时间!'}],
                                })(
                                    <Select
                                        mode="multiple"
                                        style={{width: '100%'}}
                                        onSearch={this.brandSearch}
                                        placeholder={'搜索可使用>A会显示以A开头的品牌，模糊搜索不能小于3个字母'}
                                        optionFilterProp={'children'}
                                        tokenSeparators={[',']}
                                        filterOption={false}
                                    >
                                        {brandList.map((item) => {
                                            return <Option key={item.value}>{item.name}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row style={{textAlign: 'right'}}>
                        <div style={{marginRight: 20}}>
                            <Button
                                type={'primary'}
                                style={{marginRight: 10}}
                                onClick={this.searchEnter}
                            >搜索</Button> <Button onClick={this.reset}>重置</Button>
                        </div>
                    </Row>
                    <Row style={{marginTop: 20}}>
                        <div style={{textAlign: 'left'}}>
                            <Button onClick={this.addShop} type={'primary'} style={{marginRight: 10}}>商品添加</Button>
                            <Button type={'primary'} style={{marginRight: 10}}>导出查询结果</Button>
                            <Button onClick={this.removeSelectd} type={'primary'}
                                    style={{marginRight: 10}}>停止预售并移除商品</Button>
                            <Button onClick={this.importInventory} type={'primary'} style={{marginRight: 10}}>导入经销预售库存</Button>
                        </div>
                    </Row>
                    <Row style={{marginTop: 20, marginLeft: 4, marginRight: 4}}>

                        <Table
                            loading={presellTableLoading}

                            bordered
                            className="components-table-demo-nested"
                            rowClassName={'presell_row'}
                            expandedRowKeys={expandedRowKeys}
                            columns={columns1}
                            rowSelection={rowSelection}
                            onExpandedRowsChange={this.onExpandedRowsChange}
                            expandedRowRender={this.expandedRowRender}
                            dataSource={commodityList}

                            pagination={
                                {
                                    onChange: (page,pageSize) => {
                                        console.log(page)
                                        console.log(pageSize)
                                        this.data.pageIndex = page;
                                        this.data.pageSize = pageSize;
                                        this.getPresaleList();
                                    },
                                    onShowSizeChange:(page,pageSize)=>{
                                        console.log(page)
                                        console.log(pageSize)
                                        this.data.pageIndex = page;
                                        this.data.pageSize = pageSize;

                                        this.getPresaleList();
                                    },
                                    total:total,
                                    current: this.data.pageIndex,
                                    pageSizeOptions: ['10', '20', '40', '60', '80', '100'],
                                    defaultPageSize:20,
                                    showSizeChanger:true
                                }
                            }
                        />
                    </Row>
                </div>

                <Modal
                    width={'80%'}
                    onCancel={this.HideModal({cancle: true})}
                    visible={showModal}
                    style={{maxWidth: 1000, minWidth: 800}}
                    footer={null}
                >
                    {
                        showModal &&
                        <ModalStep2 {...this.props} onModalHide={this.HideModal}></ModalStep2>
                    }

                </Modal>
                <Modal
                    width={600}
                    onCancel={this.HideModal({cancle: true})}
                    visible={inventoryModal}
                    okText={'导入'}
                    onOk={this.importInventoryEnter}
                    title={'导入经销预售库存'}
                >
                    {inventoryModal&& <div>
                        <Form.Item
                            label={'请导入Excel库存：'}
                            {...itemLayout}
                            className={'marginBottom0'}
                        >
                            {getFieldDecorator('inventoryExcelFile', {
                                rules: [
                                    {validator:(rule,value,callback)=>{
                                            console.log(value)
                                            if(!value){
                                                callback('请选择Excel上传')
                                            }else{
                                                callback()
                                            }


                                        }}
                                ]

                            })(
                                <Upload  {...imports1} >
                                    <Button>
                                        导入
                                    </Button>
                                </Upload>
                            )}
                        </Form.Item>
                        <Form.Item
                            label={' '}
                            {...excelLayout}
                        >
                            <a onClick={this.downLoad}>下载模板</a>
                        </Form.Item>
                    </div>}



                </Modal>
            </Form>

        </div>)
    }

}

export default Form.create()(Step3);